<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use addons\V4\admin\model\Order;
use think\Exception;
use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,my_total,team_total,is_active,level_id,small_total');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,my_total,team_total,mobile,team_total,level_id,small_total');
    }

//    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
//    {
//        try {
//            parent::create([
//                'uid'      => $parentId,
//                'code'     => $parentCode,
//                'algebra'  => 1,
//                'new_uid'  => $new_uid,
//                'new_code' => $new_code,
//            ]);
//            $time = time();
//            parent::where('new_uid', $parentId)
//                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,' . $new_code . ' as new_code')
//                ->selectInsert([
//                    'uid',
//                    'code',
//                    'algebra',
//                    'create_time',
//                    'update_time',
//                    'new_uid',
//                    'new_code',
//                ], (new static())->getName());
//
//            return true;
//        } catch (\Exception $e) {
//            throw new Exception($e->getMessage());
//        }
//
//    }

    public function record($uid, $code, $parent_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_id) {
                $p_id = $parent_id;
                $insert = [];
                while ($parent = User::where('id', $p_id)->field('id,code,parent_id')->find()) {
                    if ($parent) {
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_id = $parent->parent_id;
                    }
                    $algebra++;
                }
                $this->insertAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }

    //小区业绩
    public static function small_total($u_id): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $u_id)->field('id,uid,algebra')->order('algebra', 'asc')->select();
            foreach ($list as $r=>$item) {
                $num =  User::where(['parent_id'=>$item->uid,'is_active'=>2])->count();
                if($num>1)
                {
                   $areaData = User::where('parent_id', $item->uid)->field('my_total+team_total as team_total')->order('team_total', 'desc')->find();
                   $min = $item->user->team_total - $areaData->team_total;
                   User::update(['small_total'=>$min], ['id' => $item->uid]);//修改小区业绩
                }

            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //直接销售提成
    public static function sales_commission($p_uid,$uid)
    {
        $sales_commission = Cache::get('system')['sales_commission'];
        Target::Account()->basics($p_uid, 'reward', $sales_commission, '直接销售提成', '+')
            ->createBonus($uid, 1);
        if ($sales_commission > 0) {
            Event::trigger('Statistics', ['key' => 'expend', 'value' => $sales_commission]);
        }
    }

    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
//    public static function teamBonus($uid, $total, $recoil_count): array
//    {
//        try {
//
//            $list = parent::with('user')->where('new_uid', $uid)
//                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
//            $poor = 0;
//            $level_id = 0;
//            $expendTotal = 0;
//            $flat = 0;
//            $flat_open = true;
//            $recoil_tp = Cache::get('system')['recoil_tp'];
//            //$flat_total = 0;
//            foreach ($list as $item) {
//                if ($item->user->is_active != 2 || $item->user->is_out) continue;
//                //大区加速
//                if ($item->user->recoil_count <= 1 && $recoil_count <= 1) {
//                    //大区加速
//                    $areaAll = User::where('parent_id', $item->uid)->order('team_total', 'desc')
//                        ->column('my_total+team_total as team_total,id');
//                    $max_speed = Cache::get('system')['max_speed'];
//                    if (!empty($areaAll) && $max_speed > 0 && count($areaAll) > 1) {
//                        $max = array_shift($areaAll);
//                        $ids = Relation::where(['uid' => $max['id']])->column('new_uid');
//                        $ids[] = $max['id'];
//                        if (in_array($uid, $ids)) {
//                            $amount = UserRelease::testingCapping($item->uid, round($total * $max_speed, 2));
//                            $recoil = round($amount * $recoil_tp, 2);
//                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '大市场加速', '+')
//                                ->createBonus($uid, 5);
//                        }
//                    }
//                }
//                //直推
//                if ($item->algebra == 1) {
//                    $count = User::where(['is_active' => 2, 'parent_id' => $item->uid])->count();
//                    $tp = $count >= 3 ? Cache::get('system')['speed_3'] : Cache::get('system')['speed_' . $count];
//                    $amount = UserRelease::testingCapping($item->uid, round($total * $tp, 2));
//                    if ($amount > 0) {
//                        $expendTotal += $amount;
//                        $recoil = round($amount * $recoil_tp, 2);
//                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '消费分润', '+')
//                            ->createBonus($uid, 2);
//                    }
//                }
//                //团队奖
//                $level = Level::where('id', $item->user->level_id)->find();
//                if (empty($level)) continue;
//                if ($item->user->level_id > $level_id && $level->tp > $poor) {
//                    $amount = UserRelease::testingCapping($item->uid, round($total * ($level->tp - $poor), 2));
//                    if ($amount > 0) {
//                        $expendTotal += $amount;
//
//                        $recoil = round($amount * $recoil_tp, 2);
//                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '培育分润', '+')
//                            ->createBonus($uid, 3);
//                    }
//                    $poor = $level->tp;
//                    $level_id = $item->user->level_id;
//                    $flat = $item->user->level_id;
//                    $flat_open = true;
//                    //$flat_total = $amount;
//                } else {
//
//                    if ($item->user->level_id == $flat && $flat_open) {
//                        $amount = UserRelease::testingCapping($item->uid, round($total * $level->flat_tp, 2));
//                        if ($amount > 0) {
//
//                            $recoil = round($amount * $recoil_tp, 2);
//                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '平级奖', '+')
//                                ->createBonus($uid, 4);
//
//                            $expendTotal += $amount;
//                        }
//                        $flat_open = false;
//                    }
//                }
//            }
//            if ($expendTotal > 0) {
//                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
//            }
//            return ['code' => 1];
//        } catch (\Exception $e) {
//            return ['code' => -1, 'msg' => $e->getMessage()];
//        }
//    }

    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $all_id = parent::where('uid',  $item->uid)->column('new_uid');
                $num = 0;
                if (!empty($all_id)) {
                    $num = User::whereIn('id', $all_id)->where('level_id','>=',$item->user->level_id)->count();
                }
                $level = Level::where('id', '>', $item->user->level_id)
                    ->order('id', 'asc')
                    ->find();
                if ($level&&$level->superior<=$num&&$level->small<=$item->user->small_total) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }



    //团队销售提成
    public static function teamBonus($uid,$amount)
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            $level_id = 0;
            $accelerate = 0;
            $grade_id = 0;
            foreach ($list as $item) {
                if($level_id<$item->user->level_id)
                {
                    $level = Level::where('id', $item->user->level_id)->find();
                    if (empty($level)) continue;
                    $accelerate_num = $level->accelerate - $accelerate;
                    $release = bcmul((string)$amount,(string)$accelerate_num,2);
                    $residue = 0;
                    while ($order = Order::where(['uid'=>$item->uid,'order_type'=>1,'is_release'=>0,'pay_state'=>2,'delete_time'=>0])->order('id','asc')->find())
                    {
                        if($order)
                        {
                            $release = $release - $residue;
                            if($order->release + $release>=$order->green)
                            {
                                $release = $order->green - $order->release;
                                $upd['is_release'] = 1;
                                $upd['release_time'] = time();
                                Order::update($upd,['id'=>$order->id]);
                                if($release>0) {
                                    Order::where('id', $order->id)->inc('release', floatval($release))->update();
                                    Target::Account()->basics($order->uid, 'reward', $release, '团队销售提成', '+')
                                        ->createBonus($uid, 3);
                                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
                                }
                                $residue += $release;
                            }else{
                                if($release>0) {
                                    Order::where('id', $order->id)->inc('release', floatval($release))->update();
                                    Target::Account()->basics($order->uid, 'reward', $release, '团队销售提成', '+')
                                        ->createBonus($uid, 3);
                                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
                                }
                                break;
                            }
                        }
                    }
                    $level_id = $item->user->level_id;
                    $accelerate = $level->accelerate;
                }else if($level_id==$item->user->level_id&&$grade_id!=$item->user->level_id){
                    $grade = cache('system')['grade'];
                    $residue = 0;
                    $release = bcmul((string)$amount,(string)$grade,2);
                    while ($order = Order::where(['uid'=>$item->uid,'order_type'=>1,'is_release'=>0,'pay_state'=>2,'delete_time'=>0])->order('id','asc')->find())
                    {
                        if($order)
                        {
                            $release = $release - $residue;
                            if($order->release + $release>$order->green)
                            {
                                $release = $order->green - $order->release;
                                $upd['is_release'] = 1;
                                $upd['release_time'] = time();
                                Order::update($upd,['id'=>$order->id]);
                                if($release>0)
                                {
                                    Order::where('id', $order->id)->inc('release', floatval($release))->update();
                                    Target::Account()->basics($order->uid, 'reward', $release, '平级奖', '+')
                                        ->createBonus($uid, 4);
                                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
                                }
                                $residue += $release;
                            }else{
                                if($release>0)
                                {
                                    Order::where('id', $order->id)->inc('release', floatval($release))->update();
                                    Target::Account()->basics($order->uid, 'reward', $release, '平级奖', '+')
                                        ->createBonus($uid, 4);
                                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $release]);
                                }
                                break;
                            }

                        }
                    }


                    $grade_id = $item->user->level_id;
                }
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
